import axios, { AxiosInstance } from 'axios'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/user'

// eslint-disable-next-line
const baseURL = '/sapi'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL,
  timeout: 5000,
  headers: { wap: true }
  // withCredentials: true
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const store = useUserStore()
    const token_type = store.token_type || 'bearer'
    if (store.token) {
      (config as any).headers.Authorization = `${token_type} ${getToken()}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
      return Promise.reject(res)
    } else {
      return response
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
